package com.whiteblue.Interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.whiteblue.model.Book;
import com.whiteblue.model.Category;
import com.whiteblue.model.Sort;
import com.whiteblue.model.User;

/**
 * Created by WhiteBlue on 15/4/4.
 */
public class GlobalInterceptor implements Interceptor {
    @Override
    public void intercept(ActionInvocation actionInvocation) {
        Controller controller = actionInvocation.getController();
        if (controller.getSessionAttr("user") == null && (controller.getCookie("user") != null)) {
            String cookies = controller.getCookie("user");
            if (cookies.contains("-")) {
                String split[] = cookies.split("-");
                User user = User.dao.loginByCookies(split[0], split[1]);
                if (user != null) {
                    controller.setCookie("user", user.getStr("email") + "-" + user.getStr("password"), 3600 * 24 * 30);
                    controller.setSessionAttr("user", user);
                    controller.getSession().setMaxInactiveInterval(3600);
                } else {
                    controller.removeCookie("user");
                }
            } else {
                controller.removeCookie("user");
            }
        }

        if (controller.getSessionAttr("category") == null) {
            controller.setSessionAttr("category", Category.dao.listAll());
            controller.setSessionAttr("sorts", Sort.dao.listAll());
            controller.getSession().setMaxInactiveInterval(3600);
        }

        if(controller.getSessionAttr("user")!=null){
            User user=controller.getSessionAttr("user");
            controller.setAttr("msg", Book.dao.findMsg(user.getInt("id")));
        }

        if(controller.getSessionAttr("info")!=null){
            controller.setAttr("info",controller.getSessionAttr("info"));
            controller.removeSessionAttr("info");
        }


        actionInvocation.invoke();
    }
}
